<?php
class Shangku_RandomReviewsImport_Adminhtml_ReviewsController extends Mage_Adminhtml_Controller_Action
{
    protected function _isAllowed()
    {
		return Mage::getSingleton('admin/session')->isAllowed('catalog/reviews_ratings/reviews/import');
    }
    public function importAction()
    {
    	$this->_title($this->__('Catalog'))
        	->_title($this->__('Reviews and Ratings'))
            ->_title($this->__('Customer Reviews'));

        $this->_title($this->__('Random Import Reviews'));

        $this->loadLayout();
        $this->_setActiveMenu('catalog/review');

        $maxUploadSize = Mage::helper('importexport')->getMaxUploadSize();
        $this->_getSession()->addNotice(
        		$this->__('Total size of uploadable files must not exceed %s', $maxUploadSize)
        );
        
        $this->_addContent($this->getLayout()->createBlock('randomreviewsimport/adminhtml_import'));

        $this->renderLayout();
    }
    public function importPostAction()
    {
    	if($this->getRequest()->isPost() && !empty($_FILES)){
    		set_time_limit(0);
	    	$dir = Mage::getBaseDir('var') . DS . 'import' . DS . 'reviews' . DS;
	    	$uploader  = Mage::getModel('core/file_uploader',Mage_ImportExport_Model_Import::FIELD_NAME_SOURCE_FILE);
	    	$uploader->skipDbProcessing(true)
		    	->setAllowedExtensions(array('xml'))
		    	->setAllowCreateFolders(true)
		    	->setAllowRenameFiles(true);
	    	
	    	try{
		    	$result    = $uploader->save($dir);
		    	$extension = pathinfo($result['file'], PATHINFO_EXTENSION);
		    	
		    	$uploadedFile = $result['path'] . $result['file'];
		    	if (!$extension) {
		    		unlink($uploadedFile);
		    		Mage::throwException(Mage::helper('import')->__('Uploaded file has no extension'));
		    	}
		    	Mage::getModel('randomreviewsimport/import')->importReviews($uploadedFile);
	    	} catch (Exception $e) {
	    		$this->_getSession()->addError($e->getMessage());
	    		$this->_redirect('*/*/import');
	    		return;
	    	}
	    	
	    	$this->_getSession()->addSuccess($this->__('import reviews success!'));
	    	$this->_redirect('*/*/import');
	    	return;
    	}
    	
    	$this->_redirect('*/*/import');
    }
}
